#!/bin/bash

# 设置颜色变量
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # 恢复默认颜色

################## 提示变量 ##################
TEXTS=(
    "redis安装成功"
    "redis安装失败"
    "node.js安装成功"
    "node.js安装失败"
    "字体安装成功"
    "字体安装失败"
    "喵崽下载成功"
    "喵崽下载失败"
    "喵喵插件下载成功"
    "喵喵插件下载失败"
    "pnpm安装成功"
    "pnpm安装失败"
    "喵崽安装完成"
    "依赖第2次安装失败，请手动排查错误"
    "链接可访问"
    "链接不可访问"
    "JS 插件安装成功"
    "JS 插件安装失败"
    "快捷指令写入成功"
    "${RED}快捷指令写入失败${NC}"
    "ubuntu安装成功"
    "ubuntu安装失败"
    "依赖安装成功"
    "依赖安装失败，重新安装"
    "ubuntu启动成功"
    "ubuntu启动失败"
)

################## 实现通用action功能 ##################
handle_result() {
    local rc=$1
    local success_msg=$2
    local failure_msg=$3

    if [ $rc -eq 0 ]; then
        echo -e "${GREEN}[ OK ] $success_msg${NC}"
    else
        echo -e "${RED}[FAIL] $failure_msg${NC}"
        exit 1
    fi
}

# 函数，判断命令是否正常执行
if_success() {
    local ReturnStatus=$3
    handle_result "$ReturnStatus" "$1" "$2"
}


################## 系统判断 ##################

# 检查是否在安卓环境 (Termux)
if command -v getprop &> /dev/null; then
    echo -e "${YELLOW}检测到当前环境为安卓${NC}"
    sleep 3
    ID="android" # 可以为安卓环境手动设置一个 ID
else
    # 获取操作系统信息
    if [[ -f "/etc/os-release" ]]; then
        . /etc/os-release
    else
        echo "无法获取操作系统信息"
        exit 1
    fi
fi

# 读取操作系统信息
case "$ID" in
    "ubuntu"|"debian"|"centos")
        echo "支持的操作系统: $ID"
        ;;
    "android")
        echo "支持的操作系统: Android"
        ;;
    *)
        echo "不支持的操作系统: ${ID:-未识别的操作系统}"
        exit 1 
        ;;
esac

cd || exit 1

################## 环境判断 ##################
install_package() {
    local package=$1
    if ! command -v "$package" &> /dev/null; then
        echo "正在安装 $package..."
        apt-get install -y "$package"
    else
        echo "$package 已经安装."
    fi
}


################## 获取cpu架构和运行环境 ##################
exitWithError() {
    echo -e "\033[31m[ERROR] $1\033[0m" >&2
}

get_cpu_arch() {
    local commands=("$@")
    for cmd in "${commands[@]}"; do
        if command -v $cmd &> /dev/null; then
            echo "$($cmd)"
            return
        fi
    done
}

# 获取CPU架构
if command -v getprop &> /dev/null; then
    # 在安卓环境下
    AndroidVersion=$(getprop ro.build.version.release)
    if [[ -n "$AndroidVersion" ]]; then
        echo "检测到安卓环境，安卓版本:$AndroidVersion"
        CpuArch=$(get_cpu_arch "getprop ro.product.cpu.abi" "uname -m")
        sleep 3
    else
        exitWithError "无法获取安卓版本"
        exit 1
    fi
else
    # 在Linux环境下
    if [[ -f "/etc/os-release" ]]; then
        . /etc/os-release
        case "$ID" in
            "ubuntu"|"debian"|"linuxmint") 
                CpuArch=$(get_cpu_arch "dpkg-architecture -qDEB_HOST_ARCH_CPU" "uname -m")
                ;;
            "centos"|"fedora"|"rhel") 
                CpuArch=$(get_cpu_arch "uname -m" "arch")
                ;;
            *) 
                exitWithError "不支持的Linux发行版"
                exit 1 
                ;;
        esac
    else
        exitWithError "无法获取CPU架构"
        exit 1
    fi
fi


case "$CpuArch" in
    "aarch64"|"arm64"|"arm64-v8a"|"arm64_v8"|"armeabi-v7a") 
        cpu_Architecture="arm64" 
        ;;
    "x86_64"|"amd64") 
        cpu_Architecture="amd64" 
        ;;
    "armeabi") 
        cpu_Architecture="arm"  # 对于旧版 ARM 设备的支持
        ;;
    *) 
        exitWithError "无法确定CPU架构: $CpuArch" 
        exit 1 
        ;;
esac


# 获取版本
# 获取版本
if command -v getprop &> /dev/null; then
    # 安卓环境
    echo "安卓环境跳过版本检查"
    sleep 3
else
    # Linux环境
    if awk '{print $2}' /etc/issue | grep -q -E 20.04
        then
            version=20.04
            chromium_install
    elif awk '{print $2}' /etc/issue | grep -q -E 22.04
        then
            version=22.04
            chromium_install
    elif awk '{print $2}' /etc/issue | grep -q -E 22.10
        then
            version=22.10
            chromium_install
    else
        apt install -y chromium-browser || apt install -y chromium
    fi

fi


################## 浏览器安装 ##################
install_browser() {
    if ! command -v chromium-browser &> /dev/null; then
        echo -e "${YELLOW}资源来自白狐(https://gitee.com/baihu433/chromium)${NC}"
        wget -q --show-progress -O chromium-codecs-ffmpeg-extra.deb -c "https://gitee.com/baihu433/chromium/releases/download/${version}_${cpu_Architecture}/chromium-codecs-ffmpeg-extra.deb"
        wget -q --show-progress -O chromium-browser.deb -c "https://gitee.com/baihu433/chromium/releases/download/${version}_${cpu_Architecture}/chromium-browser.deb"
        wget -q --show-progress -O chromium-browser-l10n.deb -c "https://gitee.com/baihu433/chromium/releases/download/${version}_${cpu_Architecture}/chromium-browser-l10n.deb"
        apt install -yf ./chromium-codecs-ffmpeg-extra.deb ./chromium-browser.deb ./chromium-browser-l10n.deb
        rm chromium-browser.deb chromium-browser-l10n.deb chromium-codecs-ffmpeg-extra.deb
    else
        echo -e "${YELLOW}chromium-browser已安装${NC}"
    fi
}

################## 主程序 ##################
OPTION=$(whiptail --title "婉辞脚本菜单" --menu "请选择一个" 15 60 5 \
"1" "安装Miao-Yunzai" \
"2" "安装插件" \
"3" "安装ubuntu" \
"4" "签名服务器管理" \
"5" "退出脚本" 3>&1 1>&2 2>&3)

exitstatus=$?
if [ $exitstatus == 0 ]; then
    case $OPTION in
        1)
            # 安装 Miao-Yunzai
            cd || exit 1
            [ -d "Miao-Yunzai" ] && { bash <(curl -sL https://gitee.com/eulogyjiajia/miao_-script/raw/master/Script/admin.sh); exit 0; }

            Warehouse=$(whiptail --title "仓库选择" --menu "请选择一个" 15 60 4 \
            "1" "github(国外服务器选择这个)" \
            "2" "gitee(国内服务器选择这个)" 3>&1 1>&2 2>&3)

            case $Warehouse in
                1) download="github.com" ;;
                2) download="gitee.com" ;;
                *) exit 1 ;;
            esac

            apt update && apt upgrade -y
            
            # 安装redis和git
            install_package redis
            install_package git

            # 安装浏览器
            install_browser
            
            # 安装node.js
            if ! command -v node &> /dev/null; then
                curl -sL https://deb.nodesource.com/setup_20.x | bash -
                apt install -y nodejs
            fi
            
            # 检查Node.js版本
            current_version=$(node -v | tr -d 'v')
            if [[ $(echo "$current_version < 17" | bc) -eq 1 ]]; then
                echo "${YELLOW}Node.js版本过低，尝试更新Node.js${NC}"
                curl -sL https://deb.nodesource.com/setup_20.x | bash -
                apt install -y nodejs
            fi
            
            
            # 安装字体
            apt install -y --no-install-recommends fonts-wqy-microhei ttf-wqy-zenhei
            
            # 克隆Miao-Yunzai库
            git clone --depth=1 https://$download/yoimiya-kokomi/Miao-Yunzai.git
            cd Miao-Yunzai || exit 1
            
            # 克隆插件
            git clone --depth=1 https://$download/yoimiya-kokomi/miao-plugin.git ./plugins/miao-plugin/
            
            cd ..
            npm config set registry https://registry.npmmirror.com
            npm install pnpm -g
            pnpm install -P || {
                echo -e "${RED}安装依赖失败，尝试第二次安装${NC}"
                pnpm config set registry https://registry.npmmirror.com
                pnpm install -P || { echo -e "${RED}第二次安装依赖失败，请手动排查错误${NC}"; exit 1; }
            }

            npm install -g pm2 || echo -e "${RED}pm2安装失败${NC}"
            cd Miao-Yunzai
            
            if pm2 start app.js --name="miao"; then
                echo -e "${YELLOW}喵崽在后台启动${NC}"
            else
                echo -e "${RED}喵崽启动失败${NC}"
                cat logs/error.log
                exit 1
            fi
            
            ;;

        2)
            bash <(curl -sL https://gitee.com/eulogyjiajia/miao_-script/raw/master/Script/plugin.sh)
            exit 0
            ;;

        3)
            # 安装ubuntu脚本
            if ! command -v getprop &> /dev/null; then
                echo -e "非安卓环境，无法安装ubuntu镜像"
                exit 0
            elif [ -d "ubuntu22.04" ]; then
                echo -e "已有ubuntu环境，准备启动"
                cd ubuntu22.04 || exit 1
                ./startubuntu.sh
            else
                # 继续安装
                Android=$(getprop ro.build.version.release)
                Brand=$(getprop ro.product.brand)
                echo -e "尊敬的：${Brand}用户\n安卓版本：${Android}\n3秒后开始安装ubuntu镜像"
                sleep 3
                sed -i 's@^$deb.*stable main$@#\1\ndeb https://mirrors.tuna.tsinghua.edu.cn/termux/apt/termux-main stable main@' $PREFIX/etc/apt/sources.list
                apt update && apt upgrade
                
                git clone --depth=1 -b ubuntu22.04 https://gitee.com/KudouShinnyan/ubuntu-in-termux.git
                mv ubuntu-in-termux ubuntu22.04
                cd ubuntu22.04 || exit 1
                chmod +x ubuntu.sh
                apt install proot
                echo -e "正在替换ubuntu镜像源，请耐心等待"
                sleep 3
                change_ubuntu_source
                echo -e "ubuntu安装成功，10秒后会自动进入ubuntu环境\n进入后需要你自行更新软件源，并安装curl后再执行脚本，剩余的脚本会自动安装"
                sleep 10
                ./ubuntu.sh -y && ./startubuntu.sh
            fi
            ;;

        *)
            echo "错误的选择"
            exit 1
            ;;

    esac # end of case $OPTION
else
    echo "未操作，或错误" && exit 1
fi


# 定义一个功能函数调用后给ubuntu换源
function change_ubuntu_source() {
    #修改sources.list文件,不使用指令
    cat > ubuntu22.04/ubuntu-fs/etc/apt/sources.list << EOF
        deb https://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse
        deb-src https://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse

        deb https://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse
        deb-src https://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse

        deb https://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse
        deb-src https://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse

        # deb https://mirrors.aliyun.com/ubuntu/ jammy-proposed main restricted universe multiverse
        # deb-src https://mirrors.aliyun.com/ubuntu/ jammy-proposed main restricted universe multiverse

        deb https://mirrors.aliyun.com/ubuntu/ jammy-backports main restricted universe multiverse
        deb-src https://mirrors.aliyun.com/ubuntu/ jammy-backports main restricted universe multiverse

    EOF
}
